package cn.jd.pet.service.impl;


import cn.jd.basic.util.BaiduAuditUtils;
import cn.jd.pet.domain.Pet;
import cn.jd.pet.domain.PetDetail;
import cn.jd.pet.domain.PetOnlineAuditLog;
import cn.jd.pet.mapper.PetDetailMapper;
import cn.jd.pet.mapper.PetMapper;
import cn.jd.pet.mapper.PetOnlineAuditLogMapper;
import cn.jd.pet.service.IPetService;
import cn.jd.basic.service.impl.BasicServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jd
 * @since 2022-10-28
 */
@Service
public class PetServiceImpl extends BasicServiceImpl<Pet> implements IPetService {
    @Autowired
    private PetDetailMapper petDetailMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private PetOnlineAuditLogMapper petOnlineAuditLogMapper;
    @Override
    public void save(Pet pet) {
        super.save(pet);
        PetDetail petDetail = null;
        if(petDetail==null){
            PetDetail petDetail1 = new PetDetail();
        }else {
            petDetail= pet.getDetail();
        }
        pet.getDetail().setPetId(pet.getId());
        petDetailMapper.save(petDetail);
    }

    @Override
    public void update(Pet pet) {
        super.update(pet);
        pet.getDetail().setPetId(pet.getId());
        petDetailMapper.updateByPetId(pet.getDetail());
    }

    @Override
    public void onsale(List<Long> ids) {
        Map<Long, Pet> petMap = petMapper.findAll().stream().filter(pet -> pet.getState() == 0).collect(Collectors.toMap(Pet::getId, pet -> pet));
        StringBuilder builder = new StringBuilder();
        Date date = new Date();
        for (Long id : ids) {
            Pet pet = petMap.get(id);
            if(!BaiduAuditUtils.TextCensor(pet.getName())){
                builder.append("百度审核名字不通过"+pet.getResources()) ;
            }
            if(!BaiduAuditUtils.ImgCensor(pet.getResources().split(",")[0])){
                builder.append("百度审核图片不通过"+pet.getResources()) ;
            }
            if(builder.length()>0){
                // 添加失败日志
                PetOnlineAuditLog petOnlineAuditLog = new PetOnlineAuditLog();
                petOnlineAuditLog.setAuditTime(date);
                petOnlineAuditLog.setPetId(id);
                petOnlineAuditLog.setState(0);
                petOnlineAuditLog.setNote(builder.toString());
                petOnlineAuditLogMapper.save(petOnlineAuditLog);
            }
            pet.setState(1L);
            pet.setOnsaletime(date);
            petMapper.update(pet);
        }

    }

    @Override
    public void offsale(List<Long> ids) {
        petMapper.offsale(ids);
    }

    @Override
    public Pet getPetDetail(Long id) {
        return  petMapper.getPetDetail(id);
    }


}
